<?php

namespace Home\Controller;

use Common\Controller\AuthController;
use Lib\DataTable;

class AdminController extends AuthController
{
    protected static $Model;

    public function _initialize()
    {
        parent::_initialize();
        self::$Model = D('Admin');
        if(self::$AuthUser['username']!=='admin'){
            $this->ajaxReturn([
                'code' => 0,
                'info' => `只有Admin帐号有权限进行此操作`
            ]);
        }
    }

    public function all()
    {
        $Datatable = new DataTable(self::$Model);
        $Datatable->filter=array('name','username');
        $Datatable->lists();
        $Datatable->returnJson();
    }
    public function get($id)
    {
        $this->ajaxReturn(
            self::$Model->find($id)
        );
    }

    public function add()
    {
        if (!self::$Model->create()) {
            $this->ajaxReturn([
                'code' => 0,
                'info' => self::$Model->getError()
            ]);
        } else {
            self::$Model->add();
            $this->ajaxReturn([
                'code' => 1,
                'info' => '添加成功'
            ]);
        }
    }
    public function edit()
    {
        if (!self::$Model->create(I('put.'))) {
            $this->ajaxReturn([
                'code' => 0,
                'info' => self::$Model->getError()
            ]);
        } else {
            self::$Model->save();
            $this->ajaxReturn([
                'code' => 1,
                'info' => '修改成功'
            ]);
        }
    }

    public function del($id)
    {
        if (self::$Model->delete($id)) {
            $this->ajaxReturn([
                'code' => 1,
                'info' => '删除成功'
            ]);
        }else{
            $this->ajaxReturn([
                'code' => 0,
                'info' => '删除失败'
            ]);
        }
    }

}